from tkinter import *
from tkinter.ttk import *
import tkinter.messagebox as messageBox
import re

from ...utils.loggers import dev_logger, prod_logger, record_logger

from .app import HotWorkFlow
from ..master_window import GcanViewTemplate


def app_window(master=None):
    '''
        初始化加热检测窗口
        @param master: 父窗口
    '''

    '''
        玻璃加热、喷嘴加热弹出窗口
    '''
    
    # FIXME: 此处用Toplevel，不能直接用Tk生成实例，否则会报错main thread is not in mainloop
    master.userWindow = Toplevel(master)
    master.userWindow.geometry('1200x900+300+200')
    master.userWindow.title('加热检测(玻璃/喷嘴)')
    master.stepManager = HotWorkFlow(master,stepCounts= 8)

    # 初始化can盒
    master.caninit()
    

    # 隐藏主窗口
    master.withdraw()


    # 输入Vin码边框
    master.userWindowFrame1 = Frame(master.userWindow, relief='groove')
    master.userWindowFrame1.grid(row=1, column=1, padx=20, pady=20)
    # [ ]: 屏蔽VIN码输入框
    if master.stepManager.VIN_ENABLE_HOT:

        # 该组件使用的回调函数
        if 1:
            # TODO: 后期改为扫码获取值,与OBD读取值得比对
            def validateVinCode():
                # Vin码输入框验证函数
                curVin = master.curVinCode.get()
                # print(f'validate VinCode {curVin}')

                # TODO: 待开启VIN匹配功能
                pat = re.compile(r'^LNB\w{8}\d{6}$')
                if pat.match(curVin):
                # if len(curVin) > 4:
                    return True
                    
                else:
                    return False

            def validateVinCodeFailed():
                messageBox.showwarning('VIN码验证警告','VIN码验证不通过，请核对输入的VIN码是否正确？')
                # print('validate failed...')
                pass

            def curVinCodeEntryReset():
            # 清理输入框内容，获取焦点
                master.curVinCodeEntry.delete(0,END)
                master.curVinCodeEntry.focus_set()
                
                # 设置按钮使能
                # TODO: 后期将几个测试按钮的使能操作打包起来,或者用容器装起来,遍历实现可扩展性.
                

                # [ ] 待确认,重置后是否把展示状态复位?
                for wediget in master.userWindowFrame2_1TestResMsg.values():
                    dev_logger.debug('wdiget:', wediget)
                    wediget.configure(text='待检测...', foreground='gray')
                    # wediget.configure(foreground='gray')

            # 通过扫码获取vin,然后把输入框获取焦点,用于validate
            def curVinCodeScanStart():
                resultCode = master.scanner.scan()
                master.curVinCode.set(resultCode)
                master.curVinCodeEntry.focus_set()
                pass

        master.curVinCodeLabel = Label(master.userWindowFrame1, text='输入当前VIN码')
        master.curVinCodeLabel.grid(row=1, column=1, padx=10, pady=10)
        master.curVinCode = StringVar()
        master.curVinCodeEntry = Entry(master.userWindowFrame1, textvariable=master.curVinCode,validate='focusout', validatecommand=validateVinCode, invalidcommand=validateVinCodeFailed)
        master.curVinCodeEntry.grid(row=1, column=2, padx=10, pady=10)
        # master.curVinCodeConfirmBtn = Button(master.userWindowFrame1, text='确认')
        # master.curVinCodeConfirmBtn.grid(row=1, column=3, padx=10, pady=10)
        master.curVinCodeResetBtn = Button(master.userWindowFrame1, text='重置', command=curVinCodeEntryReset)
        master.curVinCodeResetBtn.grid(row=1, column=4, padx=10, pady=10)
        # TODO: 此处临时屏蔽摄像头扫码功能，待后续开启
        if 0:
            master.curVinCodeScanBtn = Button(master.userWindowFrame1, text='开始扫码', command=curVinCodeScanStart)
            master.curVinCodeScanBtn.grid(row=2,column=1, columnspan=2, padx=10, pady=10, sticky='we')


    # 步骤可视化
    master.userWindowFrame2 = Frame(master.userWindow)
    master.userWindowFrame2.grid(row=2, column=1, sticky='w', columnspan=2, padx=20, pady=20)
    if 1:
        master.userWindowFrame2_1 = Frame(master.userWindowFrame2, relief='groove')
        master.userWindowFrame2_1.grid(row=1, column=1)
        # FIXME: 通过循环，利用setattr和getattr动态操作属性，创建组件,减少代码量
        for i in range(12):
            labelIndex= 'userWindowFrame2_1StepLabel' + str(i)
            stepIndex = 'step' + str(i)
            columnIndex = i+1
            setattr(master, labelIndex, Label(master.userWindowFrame2_1, text=stepIndex))
            getattr(master, labelIndex).grid(row=2, column=columnIndex, padx=10, pady=10)

        def refreshStep(num):
            maxStep = master.stepManager.stepCounts
            # print('maxStep:', maxStep)
            for i in range(maxStep):
                labelIndex= 'userWindowFrame2_1StepLabel' + str(i)
                getattr(master, labelIndex).configure(background='gray')

            for i in range(num + 1):
                labelIndex= 'userWindowFrame2_1StepLabel' + str(i)
                getattr(master, labelIndex).configure(background='blue')
        # [ ]: 后续删除
        setattr(master, 'refreshStep', refreshStep)
        # master.refreshStep(5)

    master.userWindowFrame2_1 = Frame(master.userWindow)
    master.userWindowFrame2_1.grid(row=2, column=4, sticky='e', padx=20, pady=20)

    master.userWindowFrame2_1_Btn01 = Button(master.userWindowFrame2_1,text='重置步数0', command=master.stepManager.stepReset)
    master.userWindowFrame2_1_Btn01.grid(row=1, column=1, padx=10, pady=10)
    # step操作流程
    master.userWindowFrame3 = LabelFrame(master.userWindow, text='操作流程',  relief='raised')
    master.userWindowFrame3.grid(row=3, column=1, padx=20, pady=20, sticky='nsw')

    if 1:

        master.userWindowFrame3_Label1 = Label(master.userWindowFrame3, text='stepFlow')
        master.userWindowFrame3_Label1.grid(row=1, column=1,columnspan=3, padx=20, pady=20)


        # 开启测试和关闭测试总控制
        if 0:
            master.userWindowFrame3StepSwitchFrame = Frame(master.userWindowFrame3, relief='groove')
            master.userWindowFrame3StepSwitchFrame.grid(row=2, column=1, padx=20, pady=20)
            master.userWindowFrame3_Btn1 = Button(master.userWindowFrame3StepSwitchFrame ,  text='测试启动', command=master.stepManager.run)  
            master.userWindowFrame3_Btn1.grid(row=2, column=1, padx=20, pady=20)
            # [ ]:增加停止测试的btn按钮，尝试终止循环的方法让子线程的任务运行完毕
        # 手动启动测试
        master.stepManager.run()
        

        # 循环step明细
        if 1:
            master.userWindowFrame3StepsFrame = Frame(master.userWindowFrame3, relief='groove')
            master.userWindowFrame3StepsFrame.grid(row=3, column=1, padx=20, pady=20, sticky='nsw')

            # step 0 UI
            if 1:
                master.userWindowFrame3StepsFrameStep0Frm = LabelFrame(master.userWindowFrame3StepsFrame,text='step0', relief='groove') 
                master.userWindowFrame3StepsFrameStep0Frm.grid(row=1, column=1, padx=10, pady=10, sticky='w')
                master.userWindowFrame3StepsFrameStep0Frm_btn1 = Button(master.userWindowFrame3StepsFrameStep0Frm, text='启动检测', command=master.stepManager.step0SetFlag)
                master.userWindowFrame3StepsFrameStep0Frm_btn1.grid(row=1, column=1,padx=10, pady=10)
            if 0:
                master.userWindowFrame3StepsFrameStep1Frm = Frame(master.userWindowFrame3StepsFrame, relief='groove')
                master.userWindowFrame3StepsFrameStep1Frm.grid(row=2, column=1, padx=10, pady=10)
                master.userWindowFrame3StepsFrameStep1Frm_btn1 = Button(master.userWindowFrame3StepsFrameStep1Frm, text='step1')
                master.userWindowFrame3StepsFrameStep1Frm_btn1.grid(row=1, column=1,padx=10, pady=10)
            if 0:
                master.userWindowFrame3StepsFrameStep2Frm = Frame(master.userWindowFrame3StepsFrame, relief='groove')
                master.userWindowFrame3StepsFrameStep2Frm.grid(row=3, column=1, padx=10, pady=10)
                master.userWindowFrame3StepsFrameStep2Frm_btn1 = Button(master.userWindowFrame3StepsFrameStep2Frm, text='step2')
                master.userWindowFrame3StepsFrameStep2Frm_btn1.grid(row=1, column=1,padx=10, pady=10)
            if 1:
                master.userWindowFrame3StepsFrameStep3Frm = LabelFrame(master.userWindowFrame3StepsFrame,text='step3', relief='groove')
                master.userWindowFrame3StepsFrameStep3Frm.grid(row=4, column=1, padx=10, pady=10, sticky='w')
                # master.userWindowFrame3StepsFrameStep3Frm_btn1 = Button(master.userWindowFrame3StepsFrameStep3Frm, state=DISABLED,text='step3')
                # master.userWindowFrame3StepsFrameStep3Frm_btn1.grid(row=1, column=1,padx=10, pady=10)
                master.userWindowFrame3StepsFrameStep3Frm_boliJiareLabel = Label(master.userWindowFrame3StepsFrameStep3Frm, text='未加热...', foreground='gray')
                master.userWindowFrame3StepsFrameStep3Frm_boliJiareLabel.grid(row=1, column=2,padx=10, pady=10)
            if 0:
                master.userWindowFrame3StepsFrameStep4Frm = Frame(master.userWindowFrame3StepsFrame, relief='groove')
                master.userWindowFrame3StepsFrameStep4Frm.grid(row=5, column=1, padx=10, pady=10)
                master.userWindowFrame3StepsFrameStep4Frm_btn1 = Button(master.userWindowFrame3StepsFrameStep4Frm, text='step4')
                master.userWindowFrame3StepsFrameStep4Frm_btn1.grid(row=1, column=1,padx=10, pady=10)
            if 1:
                master.userWindowFrame3StepsFrameStep5Frm = LabelFrame(master.userWindowFrame3StepsFrame,text='step5', relief='groove')
                master.userWindowFrame3StepsFrameStep5Frm.grid(row=6, column=1, padx=10, pady=10, sticky='w')
                # master.userWindowFrame3StepsFrameStep5Frm_btn1 = Button(master.userWindowFrame3StepsFrameStep5Frm, text='step5', state=DISABLED)
                # master.userWindowFrame3StepsFrameStep5Frm_btn1.grid(row=1, column=1,padx=10, pady=10)
                master.userWindowFrame3StepsFrameStep5Frm_label1 = Label(master.userWindowFrame3StepsFrameStep5Frm, text='剩余时间:')
                master.userWindowFrame3StepsFrameStep5Frm_label1.grid(row=2, column=1,padx=0, pady=10)
                master.userWindowFrame3StepsFrameStep5Frm_label2 = Label(master.userWindowFrame3StepsFrameStep5Frm, text='**', font=('Arial', 32))
                master.userWindowFrame3StepsFrameStep5Frm_label2.grid(row=2, column=2,padx=0, pady=0)

            if 1:
                master.userWindowFrame3StepsFrameStep6Frm = LabelFrame(master.userWindowFrame3StepsFrame,text='step6', relief='groove')
                master.userWindowFrame3StepsFrameStep6Frm.grid(row=7, column=1, padx=10, pady=10, sticky='w')
                master.userWindowFrame3StepsFrameStep6Frm_btn1 = Button(master.userWindowFrame3StepsFrameStep6Frm, text='加热温度确认',state='disabled',command=master.stepManager.step6SetFlag)
                master.userWindowFrame3StepsFrameStep6Frm_btn1.grid(row=1, column=1,padx=10, pady=10)
            if 0:
                master.userWindowFrame3StepsFrameStep7Frm = Frame(master.userWindowFrame3StepsFrame, relief='groove')
                master.userWindowFrame3StepsFrameStep7Frm.grid(row=8, column=1, padx=10, pady=10)
                master.userWindowFrame3StepsFrameStep7Frm_btn1 = Button(master.userWindowFrame3StepsFrameStep7Frm, text='step7', command=master.stepManager.step7SetFlag)
                master.userWindowFrame3StepsFrameStep7Frm_btn1.grid(row=1, column=1,padx=10, pady=10)

                pass


    # 测试结果显示框
    master.userWindowFrame6_2 = Frame(master.userWindow)
    master.userWindowFrame6_2.grid(row=3,column=2, padx=20,pady=20)
    if 1:

        master.userWindowFrame6recordListboxScroll_2 = Scrollbar(master.userWindowFrame6_2, orient=VERTICAL)
        master.userWindowFrame6recordListboxScroll_2.grid(row=2, column=11, sticky="WS")
        master.userWindowFrame6recordListbox_2 = Listbox(
            master.userWindowFrame6_2,
            font=("Arial", 12),
            height=30,
            width=60,
            yscrollcommand=master.userWindowFrame6recordListboxScroll_2.set,
        )
        master.userWindowFrame6recordListbox_2.grid(row=2, column=0, columnspan=11, sticky="nw")
        master.userWindowFrame6recordListboxScroll_2.config(command=master.userWindowFrame6recordListbox_2.yview)
        master.userWindowFrame6recordClearBtn_2 = Button(
            master.userWindowFrame6_2,
            text="清空测试记录",
            command=lambda: master.userWindowFrame6recordListbox_2.delete(0,END),
        )
        master.userWindowFrame6recordClearBtn_2.grid(row=2, column=12, padx=2, pady=1)
        pass

        
    # 显示主窗口按钮
    master.userWindowFrame8 = Frame(master.userWindow)
    master.userWindowFrame8.grid(row=8, column=1, padx=20, pady=20)
    if 1:
        master.userWindowFrame8Btn1 = Button(master.userWindowFrame8,text='显示主窗口',command=master.deiconify)
        master.userWindowFrame8Btn1.grid(row=1, column=1, padx=10, pady=10)


    # 启动程序时让vin码输入框自动获取焦点
    if master.stepManager.VIN_ENABLE_HOT:
        master.curVinCodeEntry.focus_set()
